package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.SearcherService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearcherService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Autowired
    private BehaviorFeign behaviorFeign;



    @Override
    public ResponseResult search(UserSearchDto dto) {

        List<Map> resultList =new ArrayList<>();

        try{
            if(dto==null||dto.getMinBehotTime()==null || StringUtils.isBlank(dto.getSearchWords())){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //调用线程池中初始化好的线程 去执行保存方法
            //获取登录用户
            ApUser user = AppThreadLocalUtils.getUser();
            if(user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }

            //查询用户行为实体  entryId
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if(apBehaviorEntry==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apUserSearchService.insert(apBehaviorEntry.getId(),dto.getSearchWords());


            SearchRequest searchRequest =new SearchRequest("app_info_article");
            SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

            //3：组合多条件
            BoolQueryBuilder queryBuilder =QueryBuilders.boolQuery();


            //1:title or content
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR);

            queryBuilder.must(queryStringQueryBuilder);

            //pushtime 区间查询
            RangeQueryBuilder rangeQueryBuilder =QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            queryBuilder.filter(rangeQueryBuilder);


            searchSourceBuilder.query(queryBuilder);

            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);

            //分页
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());

            searchRequest.source(searchSourceBuilder);

            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            for(SearchHit hit : hits){
                String hitSourceAsString = hit.getSourceAsString();  //json串
                Map map = JSON.parseObject(hitSourceAsString, Map.class);
                resultList.add(map);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return ResponseResult.okResult(resultList);
    }
}
